package com.ymatou.shop.ui.view.item;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ymatou.shop.R;
import com.ymatou.shop.api.ApiRequest;
import com.ymatou.shop.api.ApiResponse;
import com.ymatou.shop.cache.CacheManager;
import com.ymatou.shop.cache.ImageCache;
import com.ymatou.shop.cache.OnCacheListener;
import com.ymatou.shop.cache.RequestInfo;
import com.ymatou.shop.cache.exception.CacheException;
import com.ymatou.shop.model.Comment;
import com.ymatou.shop.model.Product;
import com.ymatou.shop.model.Seller;
import com.ymatou.shop.ui.activity.ShowProductImageActivity;
import com.ymatou.shop.util.DateUtil;
import com.ymatou.shop.util.DeviceUtil;
import com.ymatou.shop.util.GlobalUtil;
import com.ymatou.shop.util.StringUtil;
import com.ymatou.shop.util.Utils;

public class EventProductItemView extends LinearLayout {
	
	private static final int REQUEST_ID_COMMENT_LIST = 0x01;
	private static final int COMMENT_NUM = 3;
	
	private TextView mTitleTextView;
	private TextView mPublishTimeTextView;
	private TextView mStockNumTextView;
	private TextView mPriceTextView;
	private TextView mCommentNumTextView;
	private LinearLayout mImageLayoutRoot;
	private LinearLayout mCommentContentRootView;
	private View mCommentMoreView;
	
	private ImageCache.OnIconLoadCompleteListener mOnIconLoadCompleteListener;
	private Product mProduct;
	private Seller mSeller;

	private int mLayoutWidth;
	private int mImageSpace = 5;
	
	private Drawable mDefaultDrawable;
	
	private View.OnClickListener mOnImageClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			String imageUrl = (String) v.getTag();
			
			Intent intent = new Intent(v.getContext(), ShowProductImageActivity.class);
			intent.putExtra(ShowProductImageActivity.EXTRA_URL_ARRAY, mProduct.mImageList);
			intent.putExtra(ShowProductImageActivity.EXTRA_URL_CURRENT, imageUrl);
			v.getContext().startActivity(intent);
		}
	};
	
	private View.OnClickListener mOnToDetailClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			GlobalUtil.startEventDetailActivity(v.getContext(), mProduct.mId, mSeller);
		}
	};
	
	public EventProductItemView(Context context, Seller seller,
			ImageCache.OnIconLoadCompleteListener iconListener) {
		super(context);

		mSeller = seller;
		mOnIconLoadCompleteListener = iconListener;
		
		int space = getResources().getDimensionPixelOffset(R.dimen.list_event_image_space);
		
		Rect rect = DeviceUtil.getScreenRect(getContext());
		mLayoutWidth = rect.width() - space * 2;
		
		mDefaultDrawable = getResources().getDrawable(R.drawable.ic_launcher);
		
		initEventItemView();
	}

	private void initEventItemView() {
		LayoutInflater.from(getContext()).inflate(R.layout.list_event_product_item, this);
		
		mTitleTextView = (TextView) findViewById(R.id.title_txt);
		mPublishTimeTextView = (TextView) findViewById(R.id.public_time_txt);
		mStockNumTextView = (TextView) findViewById(R.id.stock_num_txt);
		mPriceTextView = (TextView) findViewById(R.id.price_txt);
		mCommentNumTextView = (TextView) findViewById(R.id.comment_num_txt);
		
		findViewById(R.id.forward_root).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 转发
			}
		});
		
		findViewById(R.id.downpayment_root).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				GlobalUtil.startSaveOrderActivity(v.getContext(), mProduct);
			}
		});
		
		
		
		mTitleTextView.setOnClickListener(mOnToDetailClickListener);
		
		mImageLayoutRoot = (LinearLayout) findViewById(R.id.image_root);
		mCommentContentRootView = (LinearLayout) findViewById(R.id.comment_content_root);
		mCommentMoreView = findViewById(R.id.comment_more);
		mCommentMoreView.setOnClickListener(mOnToDetailClickListener);
		mCommentMoreView.setTag(COMMENT_NUM);
	}
	
	public void setData(Product product) {
		mProduct = product;

		mTitleTextView.setText(product.mDescription);
		mPublishTimeTextView.setText(formatPublishTime(product.mPublishTime));
		mStockNumTextView.setText(String.valueOf(product.mStockNum));
		mPriceTextView.setText(String.valueOf(product.mPrice));
		mCommentNumTextView.setText("(" + product.mCommentNum + ")");
		
		setupImageData();
		setupCommentData();
	}
	
	private void setupImageData() {
		if (mProduct.mImageList == null || mProduct.mImageList.length == 0) {
			return;
		}
		
		mImageLayoutRoot.removeAllViews();
		
		if (mProduct.mImageList.length >= 6) {
			setupImageSixData();
		} else if (mProduct.mImageList.length >= 2) {
			setupImageTwoData();
		} else {
			setupImageOneData();
		}
	}
	
	private void setupImageSixData() {
		mImageLayoutRoot.setOrientation(LinearLayout.VERTICAL);
		
		int width = mLayoutWidth / 3 - mImageSpace * 4;
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
		
		for (int i = 0; i < 2; i++) {
			LinearLayout layout = new LinearLayout(getContext());
			layout.setOrientation(LinearLayout.HORIZONTAL);
			
			ImageView imageView = createImageView();
			setImageDrawable(imageView, mProduct.mImageList[i * 3 + 0]);
			params.setMargins(0, 0, mImageSpace, 0);
			layout.addView(imageView, params);
			
			imageView = createImageView();
			setImageDrawable(imageView, mProduct.mImageList[i * 3 + 1]);
			params.setMargins(mImageSpace, 0, mImageSpace, 0);
			layout.addView(imageView, params);
			
			imageView = createImageView();
			setImageDrawable(imageView, mProduct.mImageList[i * 3 + 2]);
			params.setMargins(mImageSpace, 0, 0, 0);
			layout.addView(imageView, params);
			
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			if (i == 0) {
				layoutParams.setMargins(0, 0, 0, mImageSpace);
			} else {
				layoutParams.setMargins(0, mImageSpace, 0, 0);
			}
			mImageLayoutRoot.addView(layout, layoutParams);
		}
	}
	
	private void setupImageTwoData() {
		mImageLayoutRoot.setOrientation(LinearLayout.HORIZONTAL);
		
		int width = mLayoutWidth / 2 - mImageSpace * 2;
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
		
		ImageView imageView = createImageView();
		setImageDrawable(imageView, mProduct.mImageList[0]);
		params.setMargins(0, 0, mImageSpace, 0);
		mImageLayoutRoot.addView(imageView, params);
		
		
		imageView = createImageView();
		setImageDrawable(imageView, mProduct.mImageList[1]);
		params.setMargins(mImageSpace, 0, 0, 0);
		mImageLayoutRoot.addView(imageView, params);
	}
	
	private void setupImageOneData() {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mLayoutWidth, mLayoutWidth);
		ImageView imageView = createImageView();
		setImageDrawable(imageView, mProduct.mImageList[0]);
		mImageLayoutRoot.addView(imageView, params);
	}

	private void setImageDrawable(ImageView imageView, String url) {
		Drawable d = ImageCache.get(getContext(), url, mOnIconLoadCompleteListener);
		if (d == null) {
			d = mDefaultDrawable;
		}
		imageView.setImageDrawable(d);
		imageView.setTag(url);
		imageView.setOnClickListener(mOnImageClickListener);
	}
	
	private ImageView createImageView() {
		ImageView imageView = new ImageView(getContext());
		imageView.setScaleType(ScaleType.CENTER_CROP);
		return imageView;
	}
	
	private String formatPublishTime(Date time) {
		if (time == null) {
			return StringUtil.EMPTY_STRING;
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append("发布于");
		sb.append(Utils.formatDate(time));
		
		return sb.toString();
	}
	
	private void setupCommentData() {
		mCommentContentRootView.setVisibility(View.GONE);
		
		if (mProduct.mCommentList == null) {
			RequestInfo requestInfo = ApiRequest.getCommentList(mProduct.mId, String.valueOf(COMMENT_NUM), null);
			requestInfo.mObject = mProduct;
			CacheManager.getInstance(getContext()).register(REQUEST_ID_COMMENT_LIST, requestInfo, mOnCacheListener);
		} else {
			mCommentContentRootView.removeAllViews();
			
			for (int i = 0; i < mProduct.mCommentList.size(); i++) {
				Comment comment = mProduct.mCommentList.get(i);
				CommentItemView itemView = new CommentItemView(getContext());
				itemView.setData(comment);
				itemView.setTag(i);
				itemView.setOnClickListener(mOnToDetailClickListener);
				mCommentContentRootView.addView(itemView);
			}
			
			mCommentContentRootView.setVisibility(View.VISIBLE);
			if (mProduct.mCommentList.size() < COMMENT_NUM) {
				mCommentMoreView.setVisibility(View.GONE);
			} else {
				mCommentMoreView.setVisibility(View.VISIBLE);
			}
		}
	}
	
	private OnCacheListener mOnCacheListener = new OnCacheListener() {
		
		@Override
		public void onCacheSuccess(int requestId, RequestInfo requestInfo,
				Object response) {
			if (mProduct == requestInfo.mObject) {
				List<Comment> commentList = ApiResponse.getCommentList((String) response);
				if (commentList != null) {
					mProduct.mCommentList = commentList;
				} else {
					mProduct.mCommentList = new ArrayList<Comment>();
				}
					///////////////
						Comment comment = new Comment();
						comment.mContent = "最后一件了！！！！测试代码添加评论";
						comment.mReplyUserName = "小张";
						mProduct.mCommentList.add(comment);
						mProduct.mCommentList.add(comment);
						mProduct.mCommentList.add(comment);
						
						///////////////
				setupCommentData();
			}
		}
		
		@Override
		public void onCacheFailed(int requestId, RequestInfo requestInfo,
				CacheException error) {
			if (mProduct == requestInfo.mObject) {
				mProduct.mCommentList = new ArrayList<Comment>();
			}
		}
	};
}
